package com.hygj.baseUtil;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.ibatis.session.SqlSession;

public abstract  class BaseDaoImpl<T> implements BaseDao<T> {
    //注入session
	@Resource
	private SqlSession session;
	
	//声明反射用，获取类的反射类型
	private Class<T> clazz;
	
	@SuppressWarnings("unchecked")
	public BaseDaoImpl() {
        // 得到泛型话的超类，
        Type type = this.getClass().getGenericSuperclass();
        // 如果type集成与ParameterizedType,以为内ParameterizedType可以带有参数，可以从他里面获取参数
        Type[] args;
        if (type instanceof ParameterizedType) {
            ParameterizedType parameterizedType = (ParameterizedType) type;
            // 获取参数列表
            args = parameterizedType.getActualTypeArguments();
            if (args != null && args.length > 0) {
                // 获取地一个参数
                Type arg = args[0];
                if (arg instanceof Class) {
                    clazz = (Class<T>) arg;
                }
            }
        }
    }
   
	
	@Override
	public int insert(String sqlId, T t) {
		return session.insert(clazz.getName() + "." + sqlId, t);
	}

	@Override
	public int delete(String sqlId, Integer id) {
		return session.delete(clazz.getName() + "." + sqlId, id);
	}

	@Override
	public int update(String sqlId, T t) {
		return session.update(clazz.getName() + "." + sqlId,t);
	}

	@Override
	public T getById(String sqlId, Integer id) {
		return session.selectOne(clazz.getName() + "." + sqlId, id);
	}

	@Override
	public List<T> listAll(String sqlId, Map<String, Object> params) {
		return session.selectList(clazz.getName() + "." + sqlId, params);
	}

	public Object find(String sqlId, Map<String, Object> params){
		return session.selectOne(clazz.getName() + "." + sqlId, params);
	}
	
}
